<script setup lang="ts" name="MapContainer">
import { loadAmap } from '/@/utils/mapLoad';
import { mapProviderKey } from './constant';
import type { MapMarkerClusterOption, MapMarkerOption, MapPolygonOption, MapPolylineOption, MapProvider } from './map-type';

const props = withDefaults(
	defineProps<{
		id?: string;
	}>(),
	{
		id: 'map-container',
	}
);

onMounted(() => {
	initMap();
});

let map: any;
async function initMap() {
	try {
		await loadAmap();
		// 初始化地图
		map = new window.AMap.Map(props.id, {
			zoom: 11,
		});

		isLoaded.value = true;
		loadedCb.value?.(isLoaded.value);
	} catch (err) {
		console.error(err);
	}
}

provide<MapProvider>(mapProviderKey, {
	onLoaded,
	drawMarker,
	drawPolyline,
	drawPolygon,
	drawMarkerCluster,
});

const isLoaded = ref(false);
const loadedCb = ref();
function onLoaded(cb: (load: boolean) => void) {
	loadedCb.value = cb;
}

// 点
function drawMarker(options: MapMarkerOption, cb?: (marker: any) => void) {
	try {
		const marker = new window.AMap.Marker(options);
		map.add(marker);
		if (typeof cb === 'function') cb(marker);
	} catch (err) {
		console.error(err);
	}
}

// 线
function drawPolyline(options: MapPolylineOption, cb?: (polyline: any) => void) {
	try {
		const polyline = new window.AMap.Polyline(options);
		map.add(polyline);
		if (typeof cb === 'function') cb(polyline);
	} catch (err) {
		console.error(err);
	}
}

// 面
function drawPolygon(options: MapPolygonOption, cb?: (polygon: any) => void) {
	try {
		const polygon = new window.AMap.Polygon(options);
		map.add(polygon);
		if (typeof cb === 'function') cb(polygon);
	} catch (err) {
		console.error(err);
	}
}

// 聚合点
function drawMarkerCluster(
	dataOptions: Array<{ lnglat: [number, number][]; weight?: number }>,
	options: MapMarkerClusterOption,
	cb?: (markerCluster: any) => void
) {
	try {
		const markerCluster = new window.AMap.MarkerCluster(map, dataOptions, options);
		map.add(markerCluster);
		if (typeof cb === 'function') cb(markerCluster);
	} catch (err) {
		console.error(err);
	}
}
</script>

<template>
	<div :id="id" class="h-full w-full">
		<slot />
	</div>
</template>

<style lang="scss" scoped></style>
